package com.ssm.design.chain;

import com.ssm.design.chain.handler.AbstractHandler;
import com.ssm.design.chain.context.OrderHandleContext;
import com.ssm.design.chain.handler.v2.AbstractHandlerV2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class OrderHandlerChain<T> {



    @Autowired
    private List<AbstractHandler> chain;

    public void handle(OrderHandleContext context) {
        if (context.getPos() < chain.size()) {
            AbstractHandler handler = chain.get(context.getPos());
            // 移动位于处理器链中的位置
            context.setPos(context.getPos() + 1);
            handler.doHandle(context, this);
        }
    }




    // V2 start
    AbstractHandlerV2<T> first = new AbstractHandlerV2<T>() {
        @Override
        protected void doHandle(T o) {
        }
    };
    AbstractHandlerV2<T> end = first;

    public void addLast(AbstractHandlerV2<T> protocolProcessor) {
        end.setNext(protocolProcessor);
        end = protocolProcessor;
    }

    public void handleV2(OrderHandleContext context, T param) {
        first.doHandle(context, param);
    }
    // V2 end
}